package com.jeeplus.modules.work.queue.web;

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.FileUtils;
import com.jeeplus.modules.sys.utils.FileKit;
import com.jeeplus.modules.work.queue.service.GetGaoXinBanDataService;
import com.jeeplus.modules.work.queue.service.GetQueueDataService;
import com.jeeplus.modules.work.queue.utils.LastDateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;

@Api(tags = "数据")
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/gxb")
public class GetDataExcelController {
    //对接AppKeyValue
    @Value("${AppKeyValue}")
    private String AppKeyValue;
    private final GetQueueDataService getQueueDataService;
    private final GetGaoXinBanDataService getGaoXinBanDataService;

    @GetMapping("getDataExcel")
    @ApiOperation(value ="获取数据")
    public AjaxJson getDataExcel(HttpServletRequest request, HttpServletResponse response){
        Date date = LastDateUtil.lastFirday();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        String format = df.format(date);
        Date nowDate = new Date();
        String nowFormat = df.format(nowDate);
        List<Map<String, Object>> areaYuyuTotal = getQueueDataService.getAreaYuyuTotal();
        int lastYuyuTotal = getQueueDataService.getLastYuyuTotal(format);
        int yuyuTotal = getQueueDataService.getYuyuTotal(nowFormat);
        int pageViewTotal = getGaoXinBanDataService.getPageViewTotal();
        int registerTotal = getGaoXinBanDataService.getRegisterTotal();
        Integer takeNumberTotal = getGaoXinBanDataService.getTakeNumberTotal();


        String fileName = "高馨办访问量注册统计"+ nowFormat+".xlsx";
        //创建excle
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFCellStyle cellStyle = wb.createCellStyle();//设置样式
        cellStyle.setBorderBottom(BorderStyle.THIN);//设置下边框
        cellStyle.setBorderLeft(BorderStyle.THIN);//设置左边框
        cellStyle.setBorderRight(BorderStyle.THIN);//设置右边框
        cellStyle.setBorderTop(BorderStyle.THIN);//设置上边框
        cellStyle.setBottomBorderColor((short)1);//设置边框颜色
        cellStyle.setAlignment(HorizontalAlignment.CENTER);//居中
        //通过HSSFWorkbook创建一个HSSFFont
        HSSFFont font = wb.createFont();
        //设置一个字体的颜色2表示红色3表示绿色4表示蓝色5表示黄色6表示紫色7表示亮蓝色8表示黑色9表示白色
        font.setColor((short)8);
        //设置字体的风格：仿宋_GB2312、黑体
        font.setFontName("黑体");
        //设置一个字体的大小,此数值的取值与Excel中的字体大小取值一样
        font.setFontHeightInPoints((short) 12);
        cellStyle.setWrapText(true);//设置自动换行
        //设置背景色
        cellStyle.setFillForegroundColor((short) 13);
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        //把该字体应用到当前的样式
        font.setBold(true);
        cellStyle.setFont(font);
        String[] data = {"日期", "访问量(次)","增长率", "注册数(次)","增长率", "预约量(次）", "增长率","取号量","","区域","预约量"};
        HSSFSheet sheet = wb.createSheet("办件统计");
        //设置列宽，其中width表示Excel中的列宽值
        //firstRow：起始行 lastRow：结束行 firstCol：起始列 lastCol：结束列
        //CellRangeAddress region = new CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol);
        //sheet.addMergedRegion(region);
        try {
            HSSFRow row = null;
            HSSFCell hc = null;
            row = sheet.createRow(0);
            for(int i =0;i<data.length;i++){
                hc = row.createCell(i);
                hc.setCellStyle(cellStyle);
                hc.setCellValue(data[i]);
                sheet.setColumnWidth(i, 4000); //第一个参数代表列id(从0开始),第2个参数代表宽度值
            }

            int num = 1;
            ExecutorService pool = null;
            //加载第一次数据集合进入excle
            for(int key=0;key<areaYuyuTotal.size();key++){
                row = sheet.createRow(num);
                if(num==2){
                    row.createCell(0).setCellValue(nowFormat+"");
                    row.createCell(1).setCellValue(pageViewTotal+"");
                    row.createCell(2).setCellValue("=(B3-B2)/B2");
                    row.createCell(3).setCellValue(registerTotal+"");
                    row.createCell(4).setCellValue("=(D3-D2)/D2");
                    row.createCell(5).setCellValue(yuyuTotal+"");
                    row.createCell(6).setCellValue("=(F3-F2)/F2");
                    row.createCell(7).setCellValue(takeNumberTotal+"");
                    row.createCell(8).setCellValue("");
                    row.createCell(9).setCellValue(areaYuyuTotal.get(key).get("area")+"");
                    row.createCell(10).setCellValue(areaYuyuTotal.get(key).get("number")+"");
                }else {
                    row.createCell(9).setCellValue(areaYuyuTotal.get(key).get("area")+"");
                    row.createCell(10).setCellValue(areaYuyuTotal.get(key).get("number")+"");
                }
                num++;
            }

            //文档输出
            String fileDir = FileKit.getUserAttachmentDir("gxzw")+"excle/queue/";
            FileUtils.createDirectory(fileDir);
            fileDir = fileDir+fileName;
            OutputStream output = response.getOutputStream();
            FileOutputStream out = new FileOutputStream(fileDir);
            System.out.println(output);
            response.reset();
            //通知浏览器以下载的方式打开
            response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/msexcel");
            wb.write(output);
            out.flush();
            out.close();
            //关闭多线程
            if(null != pool){
                pool.shutdown();
            }
            return AjaxJson.success().put("url","C:/soft/web/systemImg/"+fileDir.substring(fileDir.indexOf("userfiles"),fileDir.length()));
        }catch (Exception e){}
        return AjaxJson.error("导出失败！");
    }

    @GetMapping("getGXBValue")
    @ApiOperation(value ="获取高馨办数据--对接华三智慧农城")
    public AjaxJson getGXBValue(@RequestHeader("AppKey") String AppKey){
        if (AppKeyValue.equals(AppKey)) {
            return AjaxJson.success().put("userCount",getGaoXinBanDataService.getRegisterTotal()).put("visitCount",getGaoXinBanDataService.getPageViewTotal()).put("appointmentList",getQueueDataService.getAreaYuyuTotal());
        } else {
            return AjaxJson.error("AppKey is error!").put("code", 400);
        }
    }


}
